package br.os.midlet;

import java.io.IOException;

import javax.microedition.midlet.MIDlet;
import javax.microedition.midlet.MIDletStateChangeException;

import br.os.controller.OSController;
import br.os.view.OSAutenticacao;
import br.os.view.SplashScreenForm;

import com.sun.lwuit.Dialog;
import com.sun.lwuit.Display;
import com.sun.lwuit.Form;
import com.sun.lwuit.plaf.UIManager;
import com.sun.lwuit.util.Resources;

/**
 * OSMidlet Classe principal da aplicação
 * @version 1.0
 */
public class OSMidlet extends MIDlet {
	private Form splashScreen;
	private static final int DELAY = 3000;
	private OSController osController;
	private boolean startApp       = false;
	
	/**
	 * destroyApp
	 */
	protected void destroyApp(boolean arg0) throws MIDletStateChangeException {
		startApp = false;
	}

	/**
	 * pauseApp
	 */
	protected void pauseApp() {
		startApp = false;
	}

	/**
	 * startApp
	 */
	protected void startApp() throws MIDletStateChangeException {
		if (!startApp) {
			initApp();
			osController = new OSController(this);
			Thread t = new Thread(new Runnable() {
				public void run() {
					splashScreen.show();
					try {
						splashScreen.show();
						Thread.sleep(DELAY);
						if (splashScreen.isVisible())
							osController.setOsAutenticacaoView(new OSAutenticacao(osController));
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
			});

			t.start();
			startApp = true;
		}
	}

	/**
	 *initTheme
	 */
	void initTheme() {
		try {
			Resources theme = getResources("osmobileTheme");
			UIManager.getInstance().setThemeProps(theme.getTheme(theme.getThemeResourceNames()[0]));
		} catch (IOException e) {
			Dialog.show("Exception", "Theme is null", "OK", null);
		}
	}
	
	/**
	 * initApp
	 */
	public void initApp() {
		Display.init(this);
		splashScreen = new SplashScreenForm();
		initTheme();
	}
	
	public static Resources getResources(String name) throws IOException{
		return Resources.open("/" + name + ".res");
	}

}
